<template>
  <!-- 注册弹框 -->
  <el-dialog :visible.sync="isShow" :show-close="false" width="600px" class="register" center>
    <!-- slot：title为自定义弹框的样式 -->
    <div slot="title" class="title" :show-close="false">用户注册</div>
    <!-- 表单 -->
    <el-form label-width="70px" :rules="rules" :model="form" ref="form">
      <!-- 用户头像 -->
      <el-form-item label="头像" class="iconImg" prop="avatar">
        <!-- 头像上传 ：注意action为请求的接口，name为请求接口的参数-->
        <el-upload
          class="avatar-uploader"
          :action="baseURL+'/uploads'"
          name="image"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="successUpload"
        >
          <!-- 图片上传则显示图片，否则还是显示上传图片的图标 -->
          <img v-if="form.avatar" :src="baseURL+'/'+form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- 用户名 -->
      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <!-- 邮箱 -->
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <!-- 手机 -->
      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="password" label="密码">
        <el-input show-password v-model="form.password"></el-input>
      </el-form-item>
      <!-- 图形码 -->
      <el-form-item prop="code" label="图形码">
        <!-- 栅格系统中的行 -->
        <el-row>
          <!-- 栅格系统中的列：总共为24, -->
          <el-col :span="16">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <!-- offset为该列前面空格：它的值与一行的span值加起来还是24 -->
          <el-col :span="7" :offset="1">
            <img
              class="regCode"
              :src="baseURL+'/captcha?type=sendsms'+'&id='+num"
              alt
              @click="num=Math.random()"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item prop="rcode" label="验证码">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-button class="regCode" type="primary" @click="getRcode" :disabled="totalTime!=60">
              <span v-if="totalTime!=60">({{ totalTime }}s)</span>
              <span v-else>获取用户验证码</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <!-- 弹框底部：slot：footer自定义弹框底部样式 -->
    <div slot="footer" class="footer">
      <el-button @click="isShow=false">取消</el-button>
      <el-button type="primary" @click="register">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPhoneCodeApi, registerUserAPI } from "@/api/register.js";
export default {
  data() {
    return {
      isShow: false,
      //   引入设置的基地址
      baseURL: process.env.VUE_APP_URL,
      //   form表单的各个input框绑定的值
      form: {
        username: "", //	是	string	用户名
        phone: "", //	是	string	手机号
        email: "", //	是	string	邮箱
        avatar: "", //	是	string	头像地址
        password: "", //	是	string	密码
        code: "", //	是	string	图形验证码
        rcode: "", //手机验证码
      },
      //   验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          // 表单自定义规则
          {
            validator: (rule, value, callback) => {
              let reg = /^(13[0-9]|14[57]|15[0-9]|17[067]|18[0-9])\d{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号码"));
              }
            },
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱地址"));
              }
            },
            trigger: "blur",
          },
        ],
        avatar: [{ required: true, message: "请上传头像", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 12, message: "请输入6-12位的密码", trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入图形验证码", trigger: "blur" },
          { min: 4, max: 4, message: "请输入4位字符的验证码", trigger: "blur" },
        ],
        rcode: [
          { required: true, message: "请输入手机验证码", trigger: "blur" },
        ],
      },
      //   imageUrl: "",
      // 验证码的随机数
      num: "",
      //  定时器倒计时总时间
      totalTime: 60,
    };
  },
  methods: {
    //   文件上传前的回调函数
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      // 检测图片的文件类型以及文件大小
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或者png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 文件上传成功的回调函数
    successUpload(res) {
      //   this.imageUrl = res.data.file_path;
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avater"]);
    },
    // 确定按钮验证全局表单
    register() {
      this.$refs.form.validate((result) => {
        if (result) {
          registerUserAPI(this.form).then(() => {
            this.$message.success("注册成功");
            this.isShow = false;
          });
        } else {
          this.$message.error("注册失败");
          return false;
        }
      });
    },
    //获取手机验证码:需要对手机号码和图形验证码进行单独验证，都填写了才可以获取验证码
    getRcode() {
      let num = 0; //errorMessage验证通过为空，不通过为错误提示，num记录为空的次数，当num=2时，则都通过
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        if (errorMessage == "") {
          num++;
        }
      });
      if (num === 2) {
        getPhoneCodeApi({
          phone: this.form.phone,
          code: this.form.code,
        }).then((res) => {
          //  this.$message.success('验证通过');
          this.$message.success(res.data.data.captcha + "");
          // 设置定时器,验证通过后60秒才能点击一次获取验证码
          this.totalTime--;
          var timeout = setInterval(() => {
            this.totalTime--;
            if (this.totalTime == 0) {
              clearInterval(timeout);
              this.totalTime = 60;
            }
          }, 1000);
        });
      } else {
        this.$message.error("验证失败");
      }
    },
  },
  //   使用侦听器做表单的重置：表单在关闭时，清空表单
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
      }
    },
  },
};
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    color: #fff;
    background: linear-gradient(#01c4fa, #1395fa);
  }
  .el-dialog__header {
    padding: 0;
  }
  .el-form-item__label {
    text-align: center;
  }
  .iconImg {
    text-align: center;
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  .regCode {
    width: 100%;
    height: 40px;
  }
}
</style>